package com.agile.leetcode.redenvelope;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Random;

/**
 * 算法一全称叫剩余金额随机法，听名字就知道这个方法是将剩余的金额进行随机分配，我们先来看代码。
 *
 * @Author:ChenZhangKun
 * @Date: 2022/1/24 16:36
 */
public class FirstFunction {
    public static void function_1(BigDecimal amount, BigDecimal min, BigDecimal num) {
        // 剩余红包
        BigDecimal remain = amount.subtract(min.multiply(num));
        final Random random = new Random();
        final BigDecimal hundred = new BigDecimal("100");
        BigDecimal sum = BigDecimal.ZERO;
        BigDecimal redpeck;
        for (int i = 0; i < num.intValue(); i++) {
            final int nextInt = random.nextInt(100);
            if (i == num.intValue() - 1) {
                redpeck = remain;
            } else {
                redpeck = new BigDecimal(nextInt).multiply(remain).divide(hundred, 2, RoundingMode.FLOOR);
            }
            if (remain.compareTo(redpeck) > 0) {
                remain = remain.subtract(redpeck);
            } else {
                remain = BigDecimal.ZERO;
            }
            sum = sum.add(min.add(redpeck));
            System.out.println("第" + (i + 1) + "个人抢到红包金额为：" + min.add(redpeck).setScale(2, BigDecimal.ROUND_HALF_UP));
        }
        System.out.println("红包总额：" + sum.setScale(2, BigDecimal.ROUND_HALF_UP));

    }

    public static void main(String[] args) {
        BigDecimal amount = new BigDecimal(100).setScale(2, BigDecimal.ROUND_HALF_UP);
        BigDecimal min = new BigDecimal(0.01).setScale(2, BigDecimal.ROUND_HALF_UP);
        BigDecimal num = new BigDecimal(10).setScale(2, BigDecimal.ROUND_HALF_UP);
        function_1(amount, min, num);
    }
}
